package com.yyysj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyysj.common.core.constants.Constants;
import com.yyysj.common.core.domain.Result;
import com.yyysj.common.core.domain.TableDataInfo;
import com.yyysj.common.core.enums.ResultCode;
import com.yyysj.common.security.exception.ServiceException;
import com.yyysj.system.domain.dto.QuestionAddDTO;
import com.yyysj.system.domain.dto.QuestionDTO;
import com.yyysj.system.domain.dto.QuestionEditDTO;
import com.yyysj.system.domain.dto.QuestionQueryDTO;
import com.yyysj.system.domain.es.QuestionES;
import com.yyysj.system.domain.po.Question;
import com.yyysj.system.domain.vo.QuestionDetailVO;
import com.yyysj.system.domain.vo.QuestionVO;
import com.yyysj.system.elasticsearch.QuestionRepository;
import com.yyysj.system.manager.QuestionCacheManager;
import com.yyysj.system.mapper.QuestionMapper;
import com.yyysj.system.service.IQuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class QuestionServiceImpl implements IQuestionService {

    private final QuestionMapper questionMapper;
    private final QuestionRepository questionRepository;
    private final QuestionCacheManager questionCacheManager;

//    @Override
//    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
//        //PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
//
//        List<QuestionVO> questionVOList = questionMapper.selectQuestionList(questionQueryDTO);
//        if(questionVOList == null || questionVOList.size() <= 0) {
//            return TableDataInfo.empty();
//        }
//        return TableDataInfo.success(questionVOList,questionVOList.size());
//    }

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        if (StrUtil.isNotEmpty(excludeIdStr)) {
            String[] excludeIdArr = excludeIdStr.split(Constants.SPLIT_SEM);
            Set<Long> excludeIdSet = Arrays.stream(excludeIdArr)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        List<QuestionVO> questionVOList = questionMapper.selectQuestionList(questionQueryDTO);
        Page<QuestionVO> page = (Page<QuestionVO>) questionVOList;
        if(page == null || page.getTotal() <= 0) {
            return TableDataInfo.empty();
        }
        PageInfo<QuestionVO> pageInfo = new PageInfo<>(page);
        return TableDataInfo.success(page.getResult(), pageInfo.getTotal());
    }

//    @Override
//    public Result<?> add(QuestionDTO questionDTO) {
//        Question question = new Question();
//        BeanUtils.copyProperties(questionDTO, question);
//
//        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
//                .eq(Question::getTitle, question.getTitle()));
//
//        if(CollectionUtil.isNotEmpty(questionList)) {
//            return Result.fail(ResultCode.FAILED_ALREADY_EXISTS);
//        }
//
//        int rows = questionMapper.insert(question);
//        return rows > 0 ? Result.ok() : Result.fail(ResultCode.FAILED);
//    }

    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .eq(Question::getTitle, questionAddDTO.getTitle()));
        if (CollectionUtil.isNotEmpty(questionList)) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question = new Question();
        BeanUtil.copyProperties(questionAddDTO, question);
        int insert = questionMapper.insert(question);
        if (insert <= 0) {
            return false;
        }
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question, questionES);
        questionRepository.save(questionES);
        questionCacheManager.addCache(question.getQuestionId());
        return true;
    }

    @Override
    public Result<QuestionDetailVO> detail(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if(question == null) {
            return Result.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtils.copyProperties(question,questionDetailVO);
        return Result.ok(questionDetailVO);
    }

//    @Override
//    public Result<?> updateById(QuestionDTO questionDTO) {
//        Question question = questionMapper.selectById(questionDTO.getQuestionId());
//        if(question == null) {
//            return Result.fail(ResultCode.FAILED_NOT_EXISTS);
//        }
//        BeanUtils.copyProperties(questionDTO,question);
//        int rows = questionMapper.updateById(question);
//        return rows > 0 ? Result.ok() : Result.fail(ResultCode.FAILED);
//    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question oldQuestion = questionMapper.selectById(questionEditDTO.getQuestionId());
        if (oldQuestion == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFuc(questionEditDTO.getMainFuc());
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(oldQuestion, questionES);
        questionRepository.save(questionES);
        return questionMapper.updateById(oldQuestion);
    }

    @Override
    public int delete(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        questionRepository.deleteById(questionId);
        questionCacheManager.deleteCache(questionId);
        return questionMapper.deleteById(questionId);
    }

//    @Override
//    public Result<?> deleteById(Long questionId) {
//        Question question = questionMapper.selectById(questionId);
//        if(question == null) {
//            return Result.fail(ResultCode.FAILED_NOT_EXISTS);
//        }
//        int rows = questionMapper.deleteById(questionId);
//        return rows > 0 ? Result.ok() : Result.fail(ResultCode.FAILED);
//    }
}
